package com.medical.blood.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.blood.entity.DeviceStatus;
import com.medical.blood.mapper.DeviceStatusMapper;
import org.springframework.stereotype.Service;

@Service
public class DeviceStatusService extends ServiceImpl<DeviceStatusMapper, DeviceStatus> {

    /**
     * 上传设备状态（设备主动上报数据）
     * @param status 设备状态数据
     * @return 上传结果
     */
    public boolean uploadStatus(DeviceStatus status) {
        // 1. 校验设备ID是否已存在
        DeviceStatus exist = lambdaQuery()
                .eq(DeviceStatus::getDeviceId, status.getDeviceId())
                .one();

        if (exist != null) {
            // 存在则更新
            LambdaUpdateWrapper<DeviceStatus> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(DeviceStatus::getDeviceId, status.getDeviceId())
                    .set(DeviceStatus::getOnlineStatus, status.getOnlineStatus())
                    .set(DeviceStatus::getBloodModuleStatus, status.getBloodModuleStatus())
                    .set(DeviceStatus::getCentrifugeStatus, status.getCentrifugeStatus())
                    .set(DeviceStatus::getColdStorageTemp, status.getColdStorageTemp())
                    .set(DeviceStatus::getAbnormalStatus, status.getAbnormalStatus())
                    .set(DeviceStatus::getAbnormalDesc, status.getAbnormalDesc())
                    .set(DeviceStatus::getCreateTime, status.getCreateTime());
            return update(wrapper);
        } else {
            // 不存在则新增
            return save(status);
        }
    }

    /**
     * 标记异常状态（如耗材不足、模块故障）
     * @param deviceId 设备ID
     * @param abnormalDesc 异常描述
     */
    public void markAbnormal(String deviceId, String abnormalDesc) {
        DeviceStatus status = new DeviceStatus();
        status.setDeviceId(deviceId);
        status.setAbnormalStatus(1);
        status.setAbnormalDesc(abnormalDesc);
        uploadStatus(status); // 复用上传逻辑更新状态
    }
}